package com.seeyon.bugfixtools.workflow.web;

import com.alibaba.fastjson.JSONObject;
import com.microsoft.sqlserver.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownloadController {

    Pattern sysConstPattern = Pattern.compile("(-?\\d+\\.-?\\d+_-?\\d+\\.-?\\d+)");
    Pattern formIdConstPattern = Pattern.compile("-?f=\"(-?[0-9]+?)\"");

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/index")
    public String index(){
        String sendFormId = null;
        String sql = "select idm.id,a1.resource_id,idm.view_id,idm.auth_resource_id " +
                "from CAP_FORM_AUTH_ID_MAPPING idm " +
                "left join CAP_FORM_AUTH_INFO a1 on a1.old_resource_id = idm.auth_resource_id " +
                "left join CAP_FORM_AUTH_INFO a on a.resource_id = idm.auth_resource_id " +
                "where a.id is null";
//        if(Objects.nonNull(sendFormId)){
//            sql = sql + " and idm.FORM_ID = " + sendFormId;
//        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        System.out.println("<<<<问题数据：" + list.size());
        System.out.println("--------------处理权限问题开始---------------");
        for (Map<String,Object> map : list){
            sql = "delete from CAP_FORM_AUTH_ID_MAPPING where auth_resource_id  = " + map.get("resource_id") + " and view_id = " + map.get("view_id");
            System.out.println("<<<delete sql:" + sql);
            //执行删除
            jdbcTemplate.execute(sql);
            sql = "update CAP_FORM_AUTH_ID_MAPPING set auth_resource_id = " + map.get("resource_id") +" where id = " + map.get("id");
            System.out.println("<<<update sql:" + sql);
            //执行更新
            jdbcTemplate.execute(sql);
            sql = "delete from CAP_FORM_AUTH_INFO where resource_id  = " + map.get("auth_resource_id");
            System.out.println("<<<delete sql:" + sql);
            //执行删除
            jdbcTemplate.execute(sql);
        }
        System.out.println("--------------处理权限问题结束---------------");
        System.out.println("--------------处理在途节点权限开始---------------");
        String wfSql = "SELECT count(id) FROM WF_PROCESS_RUNNING WHERE PROCESS_XML IS NOT NULL";
        int totalRows = jdbcTemplate.queryForObject(wfSql,Integer.class);
        if (0 < totalRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理WF_PROCESS_RUNNING节点权限开始---------------");
            for(int pageNum = 1; hasNum < totalRows ; pageNum ++){
                wfSql = "SELECT PROCESS_XML FROM WF_PROCESS_RUNNING wf WHERE wf.PROCESS_XML IS NOT NULL LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<WF_PROCESS_RUNNING wfsql = " + wfSql);
                List<Map<String, Object>> wfProcessList = jdbcTemplate.queryForList(wfSql);
                dealRightId(wfProcessList,"PROCESS_XML",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理WF_PROCESS_RUNNING节点权限结束---------------");
        }


        wfSql = "select count(id) from WF_PROCESS_TEMPLETE where WORKFLOW is not null";
        totalRows = jdbcTemplate.queryForObject(wfSql,Integer.class);
        if (0 < totalRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理WF_PROCESS_TEMPLETE节点权限开始---------------");
            for(int pageNum = 1; hasNum < totalRows ; pageNum ++){
                wfSql = "SELECT WORKFLOW FROM WF_PROCESS_TEMPLETE wf WHERE wf.WORKFLOW IS NOT NULL LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<WF_PROCESS_TEMPLETE wfsql = " + wfSql);
                List<Map<String, Object>> wfProcessList = jdbcTemplate.queryForList(wfSql);
                dealRightId(wfProcessList,"WORKFLOW",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理WF_PROCESS_TEMPLETE节点权限结束---------------");
        }
        wfSql = "select count(id) from WF_TEMPLETE_SHADOW_XML where WORKFLOW is not null";
        totalRows = jdbcTemplate.queryForObject(wfSql,Integer.class);
        if (0 < totalRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理 WF_TEMPLETE_SHADOW_XML 节点权限开始--------------- totalRows="+totalRows);
            for(int pageNum = 1; hasNum < totalRows ; pageNum ++){
                wfSql = "SELECT WORKFLOW FROM WF_TEMPLETE_SHADOW_XML wf WHERE wf.WORKFLOW IS NOT NULL LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<WF_TEMPLETE_SHADOW_XML wfsql=" + wfSql);
                List<Map<String, Object>> wfProcessList = jdbcTemplate.queryForList(wfSql);
                dealRightId(wfProcessList,"WORKFLOW",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理 WF_TEMPLETE_SHADOW_XML 节点权限结束---------------");
        }
        System.out.println("--------------处理在途节点权限结束---------------");
        System.out.println("---------------处理历史节点权限开始---------------");
        String affairSql = "select count(id) from ctp_affair where FORM_MULTI_OPERATION_ID is not null and IS_FINISH = 0 and is_delete = 0";
        totalRows = jdbcTemplate.queryForObject(affairSql,Integer.class);
        if (0 < totalRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理 ctp_affair 节点权限开始--------------- totalRows="+totalRows);
            for(int pageNum = 1; hasNum < totalRows ; pageNum ++){
                affairSql = "SELECT FORM_MULTI_OPERATION_ID,FORM_APP_ID FROM ctp_affair ca where ca.FORM_MULTI_OPERATION_ID IS NOT NULL AND IS_FINISH = 0 and IS_DELETE = 0 LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<ctp_affair wfsql = " + affairSql);
                List<Map<String, Object>> rightIdList = jdbcTemplate.queryForList(affairSql);
                dealCtpAffairRightId(rightIdList,"FORM_MULTI_OPERATION_ID",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理 WF_TEMPLETE_SHADOW_XML 节点权限结束---------------");
        }
        System.out.println("---------------处理历史节点权限结束---------------");

        System.out.println("---------------处理历史穿透权限开始---------------");
        String relationSql = "select count(id) from cap_form_relation_record where data_info is not null and view_through = 1";
        int totalRelationRows = jdbcTemplate.queryForObject(relationSql,Integer.class);
        if (0 < totalRelationRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理 cap_form_relation_record 历史穿透权限开始--------------- totalRows="+totalRelationRows);
            for(int pageNum = 1; hasNum < totalRelationRows ; pageNum ++){
                relationSql = "SELECT data_info,to_form_id FROM CAP_FORM_RELATION_RECORD ca WHERE ca.data_info IS NOT NULL and ca.view_through = 1 LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<relationSql wfsql=" + relationSql);
                List<Map<String, Object>> rightIdList = jdbcTemplate.queryForList(relationSql);
                dealRelationRightId(rightIdList,"data_info",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理 cap_form_relation_record 节点权限结束---------------");
        }

        String triggerSql = "select count(id) from CAP_FORM_TRIGGER_SOURCE_RECORD where view_auth is not null";
        int totalTriggerRows = jdbcTemplate.queryForObject(triggerSql,Integer.class);
        if (0 < totalTriggerRows){
            int pageSize = 5000;
            int hasNum = 0;
            System.out.println("--------------处理 CAP_FORM_TRIGGER_SOURCE_RECORD 历史穿透权限开始--------------- totalRows=" + totalTriggerRows);
            for(int pageNum = 1; hasNum < totalTriggerRows ; pageNum ++){
                triggerSql = "SELECT view_auth,source_form_id FROM CAP_FORM_TRIGGER_SOURCE_RECORD ca WHERE ca.view_auth IS NOT NULL LIMIT " + ((pageNum - 1) * pageSize)  + "," + pageSize;
                System.out.println("<<<<<triggerSql wfsql=" + triggerSql);
                List<Map<String, Object>> rightIdList = jdbcTemplate.queryForList(triggerSql);
                dealTriggerRightId(rightIdList,"view_auth",sendFormId);
                hasNum += pageSize;
            }
            System.out.println("--------------处理 CAP_FORM_TRIGGER_SOURCE_RECORD 节点权限结束---------------");
        }
        System.out.println("---------------处理历史穿透权限结束---------------");
        return "success";
    }

    private void dealRightId(List<Map<String, Object>> wfProcessList,String key,String sendFormId){
        Map<String,TreeSet<String>> idMap = new HashMap<>();
        String formId = "";
        for (Map<String,Object> map : wfProcessList){
            TreeSet<String> rightIds = new TreeSet<>();
            String processXml = (String) map.get(key);
            Matcher constantMatcher = formIdConstPattern.matcher(processXml);
            while (constantMatcher.find()){
                formId = constantMatcher.group(1);
                System.out.println(formId);
            }
            constantMatcher = sysConstPattern.matcher(processXml);
            while (constantMatcher.find()){
                String resourceId = constantMatcher.group();
                //"1.2_3.4"
                for (String viewAndRight : resourceId.split("_")){
                    //1.2
                    rightIds.add(viewAndRight);
                }
            }
            if (!StringUtils.isEmpty(formId) && 0 < rightIds.size()) {
                idMap.put(formId,rightIds);
            }
        }
        dealResult(idMap,sendFormId);
    }

    private void dealCtpAffairRightId(List<Map<String, Object>> wfProcessList,String key,String sendFormId){
        Map<String,TreeSet<String>> idMap = new HashMap<>();
        String formId = "";
        for (Map<String,Object> map : wfProcessList){
            formId = String.valueOf(map.get("form_app_id"));
            TreeSet<String> rightIds = new TreeSet<>();
            if (map.get(key).toString().contains(".")){
                for (String viewAndRight : map.get(key).toString().split("_")){
                    //1.2
                    rightIds.add(viewAndRight);
                }
                if (!StringUtils.isEmpty(formId) && 0 < rightIds.size()) {
                    if (!idMap.isEmpty() && idMap.containsKey(formId)){
                        TreeSet<String> oldRightIds = idMap.get(formId);
                        rightIds.addAll(oldRightIds);
                    }
                    idMap.put(formId,rightIds);
                }
            }
        }
        dealResult(idMap,sendFormId);
    }

    private void dealRelationRightId(List<Map<String, Object>> wfProcessList,String key,String sendFormId){
        Map<String,TreeSet<String>> idMap = new HashMap<>();
        String formId = "";
        for (Map<String,Object> map : wfProcessList){
            formId = String.valueOf(map.get("to_form_id"));
            JSONObject object = JSONObject.parseObject(map.get(key).toString());
            String pcView = object.getString("pcView");
            String phoneView = object.getString("phoneView");
            TreeSet<String> rightIds = new TreeSet<>();
            if (pcView.contains(".")){
                for (String viewAndRight : pcView.split("_")){
                    //1.2
                    rightIds.add(viewAndRight);
                }
                if (!StringUtils.isEmpty(formId) && 0 < rightIds.size()) {
                    if (!idMap.isEmpty() && idMap.containsKey(formId)){
                        TreeSet<String> oldRightIds = idMap.get(formId);
                        rightIds.addAll(oldRightIds);
                    }
                    idMap.put(formId,rightIds);
                }
            }
            if (phoneView.contains(".")){
                for (String viewAndRight : phoneView.split("_")){
                    //1.2
                    rightIds.add(viewAndRight);
                }
                if (!StringUtils.isEmpty(formId) && 0 < rightIds.size()) {
                    if (!idMap.isEmpty() && idMap.containsKey(formId)){
                        TreeSet<String> oldRightIds = idMap.get(formId);
                        rightIds.addAll(oldRightIds);
                    }
                    idMap.put(formId,rightIds);
                }
            }
        }
        dealResult(idMap,sendFormId);
    }

    private void dealTriggerRightId(List<Map<String, Object>> wfProcessList,String key,String sendFormId){
        Map<String,TreeSet<String>> idMap = new HashMap<>();
        String formId = "";
        for (Map<String,Object> map : wfProcessList){
            formId = String.valueOf(map.get("source_form_id"));
            TreeSet<String> rightIds = new TreeSet<>();
            if (map.get(key).toString().contains(".")){
                //-1508914333557568937.1715562654456365605_
                // 9166419996497432331.3035951033880954083,-7924916622273066110.2090164356758914103
                for (String viewAndRight : map.get(key).toString().split(",")){
                    for (String rightId : viewAndRight.split("_")){
                        //1.2
                        rightIds.add(viewAndRight);
                    }
                }
                if (!StringUtils.isEmpty(formId) && 0 < rightIds.size()) {
                    if (!idMap.isEmpty() && idMap.containsKey(formId)){
                        TreeSet<String> oldRightIds = idMap.get(formId);
                        rightIds.addAll(oldRightIds);
                    }
                    idMap.put(formId,rightIds);
                }
            }
        }
        dealResult(idMap,sendFormId);
    }


    private void dealResult(Map<String,TreeSet<String>> idMap,String formId){
        //处理视图权限，查询idMapping和authinf1554716892378289" h="3"/><l i="3077663393435239843" t="11" k="-5011554716892378289" j="end" h="3"/><s i="16889687318853" n="发起" t="19" o="-5011554716892378289,start,16889687o
        for (String resourceFormId : idMap.keySet()){
            if(Objects.nonNull(formId) && !Objects.equals(resourceFormId,formId)){
                continue;
            }
            for (String rightId : idMap.get(resourceFormId)){
                System.out.println("<<<<<rightId:" + rightId + " ，formId = " + resourceFormId);
                String sql = "select * from CAP_FORM_RESOURCE where id = " + rightId.split("\\.")[1];
                List<Map<String,Object>> resourceList = jdbcTemplate.queryForList(sql);
                if (0 < resourceList.size()){
                    sql = "select count(id) from CAP_FORM_AUTH_ID_MAPPING where RESOURCE_ID = " + rightId.split("\\.")[1] + " and view_id = " + rightId.split("\\.")[0] + " and form_id = " + resourceFormId;
                    int count = jdbcTemplate.queryForObject(sql,Integer.class);
                    if (0 == count){
                        JSONObject object = JSONObject.parseObject((String) resourceList.get(0).get("content"));
                        //TODO 权限未升级，需要手动插入 cap_form_auth_info、cap_form_auth_id_mapping、cap_form_auth_range
                        Long auth_resource_id = UUID.randomUUID().getMostSignificantBits();
                        System.out.println("-----------------插入的mapping auth_resource_id：" + auth_resource_id);
                        //处理mapping
                        sql = "insert into cap_form_auth_id_mapping values(?,?,?,?,?)";
                        Object[] args= {UUID.randomUUID().getMostSignificantBits(),resourceFormId,
                                rightId.split("\\.")[0],auth_resource_id,rightId.split("\\.")[1]};
                        int a = jdbcTemplate.update(sql,args);
                        System.out.println("----------a执行情况：" + a);
                        //处理cap_form_resource
                        sql = "insert into cap_form_resource values(?,?,?,?,?,?)";
                        args= new Object[]{auth_resource_id,resourceFormId,resourceList.get(0).get("resource_name"),resourceList.get(0).get("content"),
                                resourceList.get(0).get("property_type"),resourceList.get(0).get("property_name")};
                        int b = jdbcTemplate.update(sql,args);
                        System.out.println("----------b执行情况：" + b);
                        //处理auth_info
                        sql = "insert into cap_form_auth_info values(?,?,?,?,?,?,?,?,?,?,?)";
                        args= new Object[]{UUID.randomUUID().getMostSignificantBits(), resourceFormId,
                                auth_resource_id, 0, object.getString("type"), resourceList.get(0).get("resource_name"), 1, 0, resourceList.get(0).get("id"),
                                System.currentTimeMillis(), System.currentTimeMillis()};
                        int c = jdbcTemplate.update(sql,args);
                        System.out.println("----------c执行情况：" + c);
                        //处理authRange
                        sql = "insert into cap_form_auth_range values(?,?,?,?,?)";
                        args= new Object[]{UUID.randomUUID().getMostSignificantBits(),resourceFormId,auth_resource_id,"ALL","[]"};
                        int d = jdbcTemplate.update(sql,args);
                        System.out.println("----------d执行情况：" + d);
                        System.out.println("------------一条权限修复完成------------");
                    }
                }
            }
        }
    }

}
